package com.gidas.server;

import java.io.ByteArrayInputStream;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.XMLReaderFactory;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.gidas.server.PMF;

public class MyXMLParser extends DefaultHandler {

	public Date stopValidDate = new Date();
	public String city = "";

	private String logMsg = "";

	public void parse(String XMLFile, String cityName, Date validDate)
			throws Exception {
		// //System.out.println(Charset.availableCharsets());

		city = cityName;
		stopValidDate = validDate;
		// System.out.println("1Miestas: "+cityName+" ir data: "+validDate);
		// System.out.println("ßMiestas: "+city+" ir data: "+stopValidDate);
		XMLReader xr = XMLReaderFactory.createXMLReader();
		MyXMLParser handler = new MyXMLParser();
		handler.city = cityName;
		handler.stopValidDate = validDate;
		xr.setContentHandler(handler);
		xr.setErrorHandler(handler);

		ByteArrayInputStream bs = new ByteArrayInputStream(XMLFile
				.getBytes("UTF-8"));

		// FileReader r = new FileReader(XMLFile);
		xr.parse(new InputSource(bs));
	}

	public MyXMLParser() {
		super();
	}

	public void setDate(Date date) {
		this.stopValidDate = date;
		// System.out.println(date);
	}

	public void setCity(String name) {
		this.city = name;
		// System.out.println(name);

	}

	// //////////////////////////////////////////////////////////////////
	// Event handlers.
	// //////////////////////////////////////////////////////////////////

	public void startDocument() {
		// //System.out.println("Start document");
	}

	public void endDocument() {
		// //System.out.println("End document");
	}

	public void startElement(String uri, String name, String qName,
			Attributes atts) {

		// System.out.println("3Miestas: "+this.city+" ir data: "+this.stopValidDate);
		if ("".equals(uri)) {
			int attsLength = atts.getLength();
			if ((qName.compareTo("stop") == 0)) {
				// //System.out.println("Start element: stop");

				Long elementId = null;
				String elementName = "";
				String elementStreet = "";
				String elementLat = "";
				String elementLng = "";

				for (int i = 0; i < attsLength; i++) {

					if ((atts.getLocalName(i).compareToIgnoreCase("id") == 0)
							&& (atts.getValue(i) != null)) {
						elementId = Long.parseLong(atts.getValue(i));
					} else if ((atts.getLocalName(i)
							.compareToIgnoreCase("name") == 0)
							&& (atts.getValue(i) != null)) {
						elementName = atts.getValue(i);
					} else if ((atts.getLocalName(i).compareToIgnoreCase(
							"street") == 0)
							&& (atts.getValue(i) != null)) {
						elementStreet = atts.getValue(i);
					} else if ((atts.getLocalName(i).compareToIgnoreCase("lat") == 0)
							&& (atts.getValue(i) != null)) {
						elementLat = atts.getValue(i);
					} else if ((atts.getLocalName(i).compareToIgnoreCase("lng") == 0)
							&& (atts.getValue(i) != null)) {
						elementLng = atts.getValue(i);
					}

				}
				if (elementId != null && elementId != 0 && elementName != null
						&& elementName != "") {
					// System.out.println("MIESTAS! - "+city);
					// System.out.println("DATA! - "+stopValidDate);
					StopDB busStop = new StopDB(elementId, elementName,
							elementStreet, elementLat, elementLng, city,
							stopValidDate);
					int i = 0;
					// Stop busStop = new Stop();
					if (checkIfStopExist(busStop)) {
						PersistenceManager pm = PMF.get()
								.getPersistenceManager();
						try {
							/*
							 * System.out.println("irase: "+busStop.getNativeId()
							 * +" " +busStop.getName()+" "
							 * +busStop.getStreet()+" " +busStop.getLat()+" "
							 * +busStop.getLng()+" " +busStop.getCity()+" "
							 * +busStop.getStartDate() );
							 */
							pm.makePersistent(busStop);

						} finally {
							pm.close();

						}
					}
				}

			}
		}
	}

	public void endElement(String uri, String name, String qName) {
		/*
		 * if ("".equals (uri)) //System.out.println("End element: " + qName);
		 * else //System.out.println("End element:   {" + uri + "}" + name);
		 */
	}

	public void characters(char ch[], int start, int length) {
		/*
		 * System.out.print("Characters:    \""); for (int i = start; i < start
		 * + length; i++) { switch (ch[i]) { case '\\':
		 * System.out.print("\\\\"); break; case '"': System.out.print("\\\"");
		 * break; case '\n': System.out.print("\\n"); break; case '\r':
		 * System.out.print("\\r"); break; case '\t': System.out.print("\\t");
		 * break; default: System.out.print(ch[i]); break; } }
		 * System.out.print("\"\n");
		 */
	}

	// if true write
	public boolean checkIfStopExist(StopDB stop) {
		// System.out.println(stop.getNativeId());
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + StopDB.class.getName()
				+ " where nativeId == " + stop.getNativeId();
		List<StopDB> stopsList;

		try {
			/*
			 * Gali buti klaida!!! Patikrinti kas buna kai servas veluoja, nes
			 * man mete errora o po to pats pasitaise... gali buti kad kompas,
			 * gali buti bugas Pratestuoti...
			 */
			stopsList = (List<StopDB>) pm.newQuery(query).execute();
		} finally {
			pm.close();
			// System.out.println("Close pm...");
		}
		// System.out.println("Select done");
		// System.out.print("StopList.isempty2"+stopsList.isEmpty());
		return stopsList.isEmpty();

	}

	public void destroyAllStops() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + StopDB.class.getName();
		List<StopDB> stopsList = (List<StopDB>) pm.newQuery(query).execute();
		if (!stopsList.isEmpty()) {
			try {
				pm.deletePersistentAll(stopsList);
			} finally {
				pm.close();
			}

		}

	}

	public void getStopXML() {

	}

	public String getLogMsg() {
		return this.logMsg;
	}

}
